package org.r505.chatroom.global.server;
import java.io.IOException;
import java.util.Map;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.r505.chatroom.global.controller.RequestHandler;
import org.r505.chatroom.global.entity.Message;

import com.alibaba.fastjson.JSON;


@ServerEndpoint("/im.ws")
public class WebsocketEndPoint {

	Map<String, Session> users = UserQueueFactory.getInstance();

	/**
	 * 打开连接时触发
	 * 
	 * @param session
	 */
	@OnOpen
	public void onOpen(Session session) {
		//进行安全检查
		//session.getId()
		//users.put(id, session);
		System.out.println("当前用户数为: " + users.size());
	}

	/**
	 * 收到客户端消息时触发
	 * 
	 * @param message
	 * @return
	 * @throws Throwable 
	 */
	@OnMessage
	public void onMessage(Session session, String message) throws Throwable {
		Message msg = JSON.parseObject(message, Message.class);
		System.out.println("-------------------------------------------------------");
		System.out.println("key: " + msg.getType());
		System.out.println("param: " + msg.getParam());
		System.out.println("-------------------------------------------------------");
		RequestHandler.handle(session, msg.getType(), msg.getParam());
		
		//users.get(toId).getBasicRemote().sendText(message);
	}

	/**
	 * 异常时触发
	 * 
	 * @param session
	 */
	@OnError
	public void onError(Throwable throwable, Session session) {
		throwable.printStackTrace();
		System.out.println("on error");
	}

	/**
	 * 关闭连接时触发
	 * 
	 * @param relationId
	 * @param userCode
	 * @param session
	 */
	@OnClose
	public void onClose(Session session) {
		//users.remove(fromId);
		//System.out.println("user" + fromId + "has been lost connection");
	}

	public void boardcast(String message) {

		/*try {
			for (Session user : users) {
				user.getBasicRemote().sendText(message);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

	}

}